//  this library.

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:hktk_app/config/storage_key.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:intl/intl.dart';
import 'package:table_calendar/table_calendar.dart';

class TableCalendarWidget extends StatefulWidget {
  DateTime initDate;
  var onDateSelected;
  late List<dynamic> examList = [];
  late Map<DateTime, String> events = {};
  final StreamController<List<dynamic>?> controller;

  TableCalendarWidget(
      {super.key,
      required this.onDateSelected,
      required this.initDate,
      required this.examList,
      required this.controller});

  @override
  State<StatefulWidget> createState() {
    //   createState
    return _TableCalendarState();
  }
}

class _TableCalendarState extends State<TableCalendarWidget> {
  CalendarFormat _calendarFormat = CalendarFormat.month;

  // DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  DateTime? _previousMonth;

  // 所有月份考试信息
  late List<dynamic> examList;
  late List<DateTime?> haveRequestMonth = [];

  @override
  void initState() {
    super.initState();
    _selectedDay = widget.initDate!;
    _previousMonth = DateTime(widget.initDate!.year, widget.initDate!.month);
    examList = widget.examList;

    haveRequestMonth.add(_previousMonth);

    // _addEvents();
  }

  void _addEvents({required DateTime date, required String message}) {
    // _events[DateTime.utc(2023, 10, 1)] = [
    //   _Event(message, Colors.red),
    // ];
    widget.events[date] = message;
  }

  // 返回某天的考试数组
  List<String?> _getEventsForDay(DateTime day) {
    // examList;
    List<String?> eventList = [];
    for (var i = 0; i < examList.length; i++) {
      var exam = examList[i];
      if (exam['examDate'] == DateFormat('yyyy-MM-dd').format(day)) {
        eventList.add(exam["examName"] as String);
      }
    }
    return eventList;

    // 从内存获取已标记时间
    // 组合成list
    // debugPrint(day.toString());
    // 到底是string还是list
    // String? s=HiCache.getInstance().get(StorageKey.saveCalendarKey);
    // if(s!=null){
    //   List<dynamic> l=jsonDecode(s);
    //
    //   String formattedString = DateFormat('yyyy-MM-dd').format(day);
    //   var ll=l.where((element) {
    //     return formattedString==element;
    //   }).toList();
    //   if(ll.length==0) return [];
    //   String? message=HiCache.getInstance().get("calendar"+formattedString);
    //   if(message==null) return [];
    //   return [message as String];
    //   // DateTime d=DateTime.parse(formattedString);
    // }else{
    //   return [];
    // }

    // String? s = HiCache.getInstance().get(StorageKey.saveCalendarKey);
    // if (s != null) {
    //   List<String> l = json.decode(s);
    //   String formattedString = DateFormat('yyyy-MM-dd').format(day);
    //   if (l.contains(formattedString)) {
    //     String? message = HiCache.getInstance().get("calendar$formattedString");
    //     if (message != null) {
    //       return [message];
    //     }
    //   }
    // }
    // return [];
  }

  @override
  Widget build(BuildContext context) {
    // 
    // DateTime.timestamp()
    return TableCalendar(
      locale: 'zh_CN',
      firstDay: DateTime.now(),
      lastDay:
          DateTime.utc(DateTime.now().year + 1, DateTime.now().month + 1, 28),
      focusedDay: _selectedDay ?? DateTime.now(),
      calendarFormat: _calendarFormat,
      // 决定是否显示选中样式
      selectedDayPredicate: (day) {
        return isSameDay(_selectedDay, day);
      },
      onDaySelected: (selectedDay, focusedDay) {
        if (!isSameDay(_selectedDay, selectedDay)) {
          setState(() {
            _selectedDay = selectedDay;
            // _focusedDay = focusedDay;
          });
          widget.onDateSelected(selectedDay, examList);
        }
      },
      onFormatChanged: (format) {
        setState(() {
          _calendarFormat = format;
        });
      },
      // 切换月份,切换选中日期，不切换导致不聚焦的bug
      onPageChanged: (focusedDay) {
        _selectedDay = focusedDay;
        final currentMonth = DateTime(focusedDay.year, focusedDay.month);
        if (_previousMonth != null && currentMonth != _previousMonth) {
          _previousMonth = currentMonth; // 更新上一次的月份记录
          // 如果已经获取过，则不发生什么

          if (haveRequestMonth.contains(currentMonth)) {
            handleExamDataOnPageChange(currentMonth, examList,false);
          } else {
            //   获取考试日历并更新
            MyDao.getCalendar(focusedDay.year, focusedDay.month).then((data) {
              handleExamDataOnPageChange(currentMonth, data,true);
            });
          }
        }
      },
      eventLoader: _getEventsForDay,
      calendarBuilders: CalendarBuilders(
        markerBuilder: (context, day, events) {
          if (events.length > 0) {
            return Container(
              margin: EdgeInsets.all(4.0),
              decoration:
                  BoxDecoration(shape: BoxShape.circle, color: Color(0x4fff0000)
                      // color: events[0].color.withOpacity(0.5),
                      ),
              child: Center(
                  // child: Text(
                  //  day.day.toString(),
                  //   style: TextStyle(color: Colors.red),
                  // ),
                  ),
            );
          }
          return null;
        },
        // dowBuilder: (context, day) {
        //   if (day.weekday == DateTime.sunday) {
        //     final text = DateFormat.E().format(day);
        //
        //     return Center(
        //       child: Text(
        //         text,
        //         style: TextStyle(color: Colors.red),
        //       ),
        //     );
        //   }
        // },

        // singleMarkerBuilder: (context, date, events) {
        //   debugPrint("9999999999999"+date.toString());
        //   if (date == DateTime.now()) {
        //
        //     return Container(
        //       decoration: BoxDecoration(
        //         shape: BoxShape.circle,
        //         color: Colors.red, // 标注颜色
        //       ),
        //       child: Center(
        //         child: Text(
        //           date.day.toString(),
        //           style: TextStyle(color: Colors.white),
        //         ),
        //       ),
        //     );
        //   }
        //   return null; // 其他日期不标注
        // },
      ),
      headerStyle: HeaderStyle(
        formatButtonVisible: false, // 隐藏格式按钮
        titleCentered: true,
      ),
    );
  }

  handleExamDataOnPageChange(DateTime currentMonth, List<dynamic> data,bool isRequest) {
    if (data.length > 0) {
      if(isRequest){
        examList.addAll(data);
        haveRequestMonth.add(currentMonth);
      }


      // widget.onDateSelected(selectedDay, examList);
      widget.onDateSelected(_selectedDay, examList);

      setState(() {

      });



      // widget.controller.add(examList.where((e) {
      //   return isSameDay(currentMonth,
      //       DateFormat("yyyy-MM-dd").parse(e['examDate'] as String));
      // }).map((e) {
      //   return e["examName"] as String;
      // }).toList());
      // setState(() {});
    } else {
      // setState(() {
      //   widget.controller.add([]);
      // });



      widget.onDateSelected(_selectedDay, examList);

      setState(() {

      });
    }
  }
}
